package com.iteaj.util;

import com.iteaj.util.core.UtilsException;
import com.iteaj.util.core.UtilsType;
import com.iteaj.util.json.Json;
import com.iteaj.util.json.JsonAdapter;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

public final class JsonUtils {

	static JsonAdapter adapter;

	static {
		try {
			Class<?> aClass = Class.forName("com.iteaj.util.json.jackson.JacksonAdapter"
					, true, JsonUtils.class.getClassLoader());
			adapter = (JsonAdapter) aClass.newInstance();
		} catch (Throwable e) {
			try {
				Class<?> aClass = Class.forName("com.iteaj.util.json.fastjson.FastJsonAdapter"
						, true, JsonUtils.class.getClassLoader());
				adapter = (JsonAdapter) aClass.newInstance();
			} catch (Throwable te) {
				throw new UtilsException("请引入jar包[fastjson or jackson]", UtilsType.JSON);
			}
		}
	}

	public static String toJson(Object obj) {
		return adapter.toJson(obj);
	}

	public static String toJson(Object obj, SimpleDateFormat format) {
		return adapter.toJson(obj, format);
	}

	public static  <T> T toBean(String json, Class<T> clazz) {
		return (T) adapter.toBean(json, clazz);
	}

	public static  <T> List<T> toList(String json, Class<T> elementType) {
		return adapter.toList(json, elementType);
	}

	public static <T> T toArray(String json, Class<T> arrayType) {
		return (T) adapter.toArray(json, arrayType);
	}

	public static  <K, V> Map<K, V> toMap(String json, Class<? extends Map> mapType, Class<K> keyType, Class<V> valueType) {
		return adapter.toMap(json, mapType, keyType, valueType);
	}

	public static Json builder() {
		return adapter.builder();
	}

	public static Json builder(String json) {
		return adapter.builder(json);
	}

}
